package com.foodorder.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis配置类
 */
@Configuration
public class RedisConfig {
    
    private static final Logger log = LoggerFactory.getLogger(RedisConfig.class);
    
    /**
     * RedisTemplate配置
     * 只有在Redis可用时才创建
     */
    @Bean
    @ConditionalOnProperty(name = "spring.data.redis.host")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        log.info("配置Redis连接...");
        
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        
        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        
        log.info("Redis配置完成");
        return template;
    }
    
    /**
     * 当Redis不可用时，提供一个空的RedisTemplate
     */
    @Bean
    @ConditionalOnProperty(name = "spring.data.redis.host", havingValue = "", matchIfMissing = true)
    public RedisTemplate<String, Object> mockRedisTemplate() {
        log.warn("Redis未配置，使用Mock RedisTemplate");
        return new MockRedisTemplate<>();
    }
    
    /**
     * Mock RedisTemplate实现
     * 当Redis不可用时提供基本的内存缓存功能
     */
    public static class MockRedisTemplate<K, V> extends RedisTemplate<K, V> {
        
        private static final Logger log = LoggerFactory.getLogger(MockRedisTemplate.class);
        
        @Override
        public void afterPropertiesSet() {
            log.info("使用Mock RedisTemplate（内存缓存）");
            // 不调用父类的afterPropertiesSet，避免连接Redis
        }
        
        // 可以在这里实现简单的内存缓存逻辑
        // 为了简化，这里只是记录日志，实际操作会被忽略
    }
} 